#include <cassert>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <sstream>
#include <fstream>
#include <memory>
#include <string>
#include "koopa_parse.hpp"
#include "ast.hpp"
#include "exp.hpp"

using namespace std;

extern FILE *yyin;
extern int yyparse(unique_ptr<BaseAST> &ast);

void PrintSource(const char *input) {
	char one_line[150];
	ifstream input_file(input);
	while (!input_file.eof()) {
		input_file.getline(one_line, 150);
		cout << one_line << endl;
	}
}

int main(int argc, const char *argv[]) {
	assert(argc == 5);
	auto mode = argv[1];
	auto input = argv[2];
	auto output = argv[4];

	// 打印源SysY程序
	PrintSource(input);
	
	// 将输入文件设为flex输入流
	yyin = fopen(input, "r");
	assert(yyin);

	// 保存cout的streambuf，将cout重定向为字符串流koopa_ir
	stringstream koopa_ir;

	unique_ptr<BaseAST> ast;
	auto ret = yyparse(ast);
	assert(!ret);

	ast->Dump(koopa_ir);

 	if (strcmp(mode, "-koopa") == 0) {
		ofstream of(output);
		of << koopa_ir.str();
		of.close();
		
	} else if (strcmp(mode, "-riscv") == 0) {
		stringstream riscv_code;
		ofstream of;
		of.open(output);
		KoopaParse(koopa_ir.str().c_str(), riscv_code);
		of << riscv_code.str();
		of.close();
	} else { cerr << "miss option" << endl; }

	return 0;
}

